<?php

namespace backend\controllers;

use Yii;
use Exception;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\validators\FileValidator;
use common\models\CdnConfig;

/**
 * 上传控制器
 * Class FileController
 * @property UploadedFile $file
 * @package backend\controllers
 */
class FileController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * @var UploadedFile
     */
    protected $file;


    public function actionCheck()
    {
        try {
            if (request()->isPost) {
                $filePath = str_replace(['/','\\','.'],'',(string)post('uploadPath','default'));
                $fileName = post('fileName');

                //定义上传 目录 相对路径
                $relativePath = '/upload/'.$filePath.'/'.substr($fileName,0,2). '/' .$fileName;

                $file = Yii::getAlias('@webroot'.$relativePath);

                if(is_file($file)){
                    return $this->asSuccessJson([
                        'fileUrl' => request()->getHostInfo().$relativePath,
                        'relativePath' => $relativePath,
                        'absolutePath' => $file,
                    ]);
                }else{
                    return $this->asErrorJson('文件校验失败.');
                }
            }
        }catch (Exception $e){
            exceptionFormat($e);
            return $this->asErrorJson('文件校验失败.');
        }
    }

    /**
     * actionWandEditorImage
     * @return Response
     */
    public function actionWandEditorImage()
    {
        try {
            if (request()->isPost) {
                foreach ($_FILES as $key => $file) {
                    $res = $this->saveFile('image',$key);
                    $data[] = $res['fileUrl'];
                }
                return $this->asJson([
                    'errno' => 0,
                    'data' => $data,
                ]);
            }
        }catch (Exception $e){
            exceptionFormat($e);
            return $this->asJson([
                'errno' => $e->getCode(),
                'message' => $e->getMessage(),
            ]);
        }
    }

    /**
     * actionUpload
     * @return Response
     */
    public function actionUpload()
    {
        try {
            if (request()->isAjax) {

                $this->file = UploadedFile::getInstanceByName('file');

                $type = 'default';

                foreach (params('upload') as $uploadType => $uploadConfig){
                    if(false !== stripos($uploadConfig['extensions'],$this->file->extension)){
                        $type = $uploadType;
                        break;
                    }
                }

                return $this->asSuccessJson($this->saveFile($type),'上传文件成功');
            }
        }catch (Exception $e){
            exceptionFormat($e);
            return $this->asErrorJson($e->getMessage());
        }
    }

    /**
     * saveFile
     * @param string $name
     * @param string $file
     * @return array
     * @throws Exception
     */
    protected function saveFile($name='image',$file='file')
    {
        if(empty($this->file)){
            $this->file = UploadedFile::getInstanceByName($file);
        }

        $validatorConfig = params('upload')[$name]??[];

        $validate = new FileValidator($validatorConfig);

        $validate->skipOnEmpty = false;

        $validate->validate($this->file,$error);

        if (!empty($error)) {
            throw new Exception($error);
        }

        //文件名
        $fileName = md5_file($this->file->tempName);
        //根目录
        $webroot = Yii::getAlias('@webroot');

        //定义上传 目录 相对路径
        $filePath = str_replace(['/','\\','.'],'',(string)post('uploadPath','default'));
        $relativePath = '/upload/'.$filePath.'/'.substr($fileName,0,2). '/' .$fileName. "." . $this->file->extension;
        //绝对 路径
        $absolutePath = $webroot.$relativePath;
        $flag = false;
        if(!is_file($absolutePath)){
            //创建 文件夹
            FileHelper::createDirectory(dirname($absolutePath));
            $result = $this->file->saveAs($absolutePath);
            if(!$result){
                throw new Exception('上传文件失败');
            }
            $flag = true;
        }else{
            @unlink($this->file->tempName);
        }
        $imageUrl = request()->getHostInfo().$relativePath;
        // cdn 文件上传
        if(!empty($cdnUpload = CdnConfig::getTarget())){
            $flag && $cdnUpload->upload($absolutePath,substr($relativePath, 1));
            $imageUrl = $cdnUpload->getCdnUrl($relativePath);
        }

        return [
            'fileUrl' => $imageUrl,
            'relativePath' => $relativePath,
            'absolutePath' => $absolutePath,
        ];

    }

}
